package com.fuyun.microservice.connect;

import com.fuyun.microservice.codec.*;
import com.fuyun.microservice.config.SslProperties;
import com.fuyun.microservice.handler.*;
import com.fuyun.microservice.proxy.ForwardFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.ssl.SslHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLEngine;

@Slf4j
@Component
public class CodecChannelInitializer extends io.netty.channel.ChannelInitializer<Channel> {

    @Autowired
    ForwardFactory forwardFactory;

    @Autowired
    SessionManager sessionManager;

    @Autowired
    BroadMessageAdaptor broadMessageAdaptor;

    @Autowired
    SslProperties sslProperties;

    @Override
    protected void initChannel(Channel ch) {
        SSLEngine engine = SslContextFactory.getServerContext(sslProperties.getStorePath(), sslProperties.getStorePass(), sslProperties.getPrivateKeyPass()).createSSLEngine();
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(false);

        ChannelPipeline pipeline = ch.pipeline();
        pipeline
                .addFirst("ssl", new SslHandler(engine))
                .addLast(new ServerIdleStateHandler())
                .addLast(new ChannelStateHandler(sessionManager))
                .addLast(new FrameDecoder())
                .addLast(new HeaderCodec())
                .addLast(new MessageLogHandler())
                .addLast(new LoginRequestMessageCodec())
                .addLast(new LoginResponseMessageCodec())
                .addLast(new LoginHandler(sessionManager))
                .addLast(new QueryRequestMessageCodec())
                .addLast(new QueryResponseMessageCodec())
                .addLast(EventLoopGroupFactory.proxyGroup, new ProxyMessageHandler(forwardFactory))
                .addLast(new BroadRequestMessageCodes())
                .addLast(new BroadcastAckHandler(broadMessageAdaptor))
                .addLast(new HeartbeatMessageHandler());
    }
}
